package userdisplays;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.TreeMap;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import users.User;

import networkedmodules.Module;
import networkedmodules.ModuleGroup;

public class UserPanelGroup extends Module {
	private User owner;
	protected Map<User, JPanel> panels;
	private JPanel container;

	/**
	 * 
	 * @param user
	 *            The User for whom this application instance exists
	 */
	public UserPanelGroup(User owner) {
		this.owner = owner;
		container = new JPanel();
		container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
		panels = new TreeMap<User, JPanel>();
	}

	public JPanel getPanel() {
		return container;
	}

	public void putPanel(User user, UserPanel panel) {
		JPanel holder = panels.get(user);
		if (holder == null) {
			holder = new JPanel();
			container.add(holder);
			holder.add(panel);
			panels.put(user, holder);
			panel.setUserPanelGroup(this);
			getModuleGroup().sendUpdate(new NewPanelUpdate(user, panel));
		} else {
			holder.removeAll();
			holder.add(panel);
			panel.setUserPanelGroup(this);
		}
		try {
			SwingUtilities.invokeAndWait(new Runnable() {
				public void run() {
					container.validate();
					container.repaint();
				}
			});
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Only the owner may edit their panel
		if(!owner.equals(user) && this.getModuleGroup().getType() == ModuleGroup.CLIENT)
		{
			panel.lock();
		}
	}
}
